import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
import pinia from './store'
import panelHead from './components/panelHead.vue'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

const app = createApp(App)

// Pinia挂载
app.use(pinia)

// 导入菜单 store
import { useMenuStore } from './store/menu'

//刷新后的动态路由添加
const localData = localStorage.getItem('pz_v3pz')
if (localData) {
  const menuStore = useMenuStore()
  const parsedData = JSON.parse(localData)
  const routerList = parsedData.routerList || []
  if (routerList.length > 0) {
    menuStore.dynamicMenu(routerList)
    menuStore.routerList.forEach(item => {
      router.addRoute('main', item)
    })
  }
}

//添加路由守卫进行判断
//实现 “未登录拦截” 和 “已登录重定向” 的功能
router.beforeEach((to, from) => {
  //从本地缓存获取 token（用户登录状态的凭证）
  const token = localStorage.getItem('pz_token')
  //非登录页面token不存在
  //未登录用户访问非登录页 → 强制跳转到登录页
  if (!token && to.path !=='/login') {
      return '/login'
  } 
    //token存在且访问login页面
  //已登录用户访问登录页 → 强制跳转到首页
  else if (token && to.path ==='/login') {
     return '/'
  }
  //其它情况
  else {
    return true
  }
})


import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import PanelHead from './components/panelHead.vue'

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}
app.component('PanelHead',PanelHead)
//路由挂载
app.use(router) 
app.use(ElementPlus)
app.mount('#app')

